package mobi.bantu.utils;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * Created by tancw on 2017/2/13.
 */

public class TokenUtil {

//    private static final String APPID = SysConf.get("weixin.appID");
//    private static final String APP_SEC = SysConf.get("weixin.appsecret");

    static String APPID = "wxc76382e21021363b";
    static String APP_SEC = "5b9da9954a014568c132b8127e0e021c";

    public static String getJsApiTicket() {
        String key = "jsApi" + APPID;
        String apiTicket = LocalCacheUtils.get(key);
        String jsonStr = null;

        if (StringUtils.isBlank(apiTicket)) {
            String e = getToken(false);
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + e + "&type=jsapi";
            jsonStr = HttpUtil.get(url);
            JSONObject object = JSON.parseObject(jsonStr);
            apiTicket = object.getString("ticket");
            if (apiTicket != null) {
                LocalCacheUtils.add(key, apiTicket);
            }
        }
        return apiTicket;
    }

    public static String initToken(boolean fresh) {
        String token = LocalCacheUtils.get(APPID);
        if (!fresh && StringUtils.isNotBlank(token)) {
            return token;
        }
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APP_SEC);
        String jsonStr = HttpUtil.get(url);
        JSONObject object = JSON.parseObject(jsonStr);
        token = object.getString("access_token");
        if (StringUtils.isNotBlank(token)) {
            LocalCacheUtils.add(APPID, token);
        }
        return token;
    }

    public static String getToken(boolean fresh) {
        return initToken(fresh);
    }

}
